package Server;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;

public class Search implements Serializable {

	List<DocumentData> results;

	public Search() throws Exception {
		results = new ArrayList<DocumentData>();
	}

	public List<DocumentData> doSearch(String searchTerm) throws IOException,
			ParseException {
		String indexPath = "index";
		IndexReader reader = DirectoryReader.open(FSDirectory.open(new File(
				indexPath)));
		IndexSearcher searcher = new IndexSearcher(reader);
		Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_40);
		QueryParser parser = new QueryParser(Version.LUCENE_40, "SUMMARY",
				analyzer);
		Query query = parser.parse(searchTerm);

		TopDocs topDocs = searcher.search(query, 100);
		ScoreDoc[] hits = topDocs.scoreDocs;

		results.clear();

		for (ScoreDoc scoreDoc : hits) {
			Document doc = searcher.doc(scoreDoc.doc);
			String docNo = doc.get("DOCNO");
			String summary = doc.get("SUMMARY");
			String docTitle = doc.get("DOCTITLE");
			DocumentData dd = new DocumentData(summary, docNo, docTitle);
			results.add(dd);
		}

		return results;

	}

}
